package com.tansty.security.config.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tansty.security.mapper.UserMapper;
import com.tansty.security.pojo.Permission;
import com.tansty.security.pojo.Role;
import com.tansty.security.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * description: 用户认证 <br>
 * date: 2021/8/1 15:14 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    MyPasswordEncoder passwordEncoder ;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名去数据库中查询
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", username));
        if(user==null){
            return null;
        }else {
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            // 数据库中查询出所拥有的角色进行赋予
            for (Role role : userMapper.findRoleByUsername(username)) {
                authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
            // 数据库中查出所具有的权限进行授权
            for (Permission permission : userMapper.findPermissionByUsername(username)) {
                authorities.add(new SimpleGrantedAuthority(permission.getPermTag()));
            }
            org.springframework.security.core.userdetails.User authUser = new org.springframework.security.core.userdetails.User(
                user.getUserName(), passwordEncoder.encode(user.getPassword()), authorities
            );
            return authUser;
        }
    }

}
